import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:gameplay_flutter/generated/assets.dart';
import 'package:gameplay_flutter/lib_basemodel/user/user.dart';
import 'package:gameplay_flutter/lib_baseview/lib_baseview.dart';
import 'package:gameplay_flutter/lib_baseview/theme/jr.dart';
import 'package:gameplay_flutter/lib_im/index.dart';
import 'package:gameplay_flutter/lib_runtime/extension/widget/widget_wrapper.dart';
import 'package:gameplay_flutter/lib_user/user_manager.dart';
import 'package:gameplay_flutter/m_discover/post/post_view.dart';
import 'package:gameplay_flutter/m_discover/post_detail/post_detail_view.dart';
import 'package:gameplay_flutter/m_me/constants/me_assets_constants.dart';
import 'package:gameplay_flutter/m_me/me_controller.dart';
import 'package:gameplay_flutter/m_me/user_deit_page/user_edit_page.dart';
import 'package:gameplay_flutter/m_me/user_details_page/custom_tab_bar_indicator.dart';
import 'package:gameplay_flutter/m_me/user_details_page/user_details_page_controller.dart';
import 'package:ones/ui.dart';
import 'package:ones/ui/rounded_rectangle.dart';

import '../../resource/language/generated/l10n.dart';

/// 用户详情页面
/// 使用NestedScrollView实现可折叠的头部效果
class MeDetailsPage extends StatefulWidget {

  const MeDetailsPage({super.key});

  @override
  State<MeDetailsPage> createState() => _MeDetailsPageState();
}

class _MeDetailsPageState extends State<MeDetailsPage>
    with SingleTickerProviderStateMixin {
  late final MeController meController;

  /// Tab页控制器
  late TabController _tabController;

  /// 滚动控制器，用于监听滚动位置实现头部折叠效果
  late ScrollController _scrollController;

  /// Tab页标题列表
  final List<String> _tabs = ['My Dynamics', 'My Likes'];

  /// 头部是否已折叠的状态标记
  bool _isCollapsed = false;
  bool _isMe = true;

  double get _appBarHeight =>
      kToolbarHeight + MediaQuery.of(context).padding.top;

  @override
  void initState() {
    super.initState();
    meController = Get.put(MeController());
    String meId = UserManager.instance.currentUser?.id.toString() ?? "0";
    meController.getUserMine(userId: meId);

    // 初始化滚动控制器
    _scrollController = ScrollController();
    // 初始化Tab控制器
    _tabController = TabController(length: _tabs.length, vsync: this);
    // 添加滚动监听，根据滚动位置更新头部折叠状态
    _scrollController.addListener(() {
      final isCollapsed = _scrollController.hasClients &&
          _scrollController.offset > (300 - kToolbarHeight);
      if (isCollapsed != _isCollapsed) {
        setState(() {
          _isCollapsed = isCollapsed;
        });
      }
    });
  }

  @override
  void dispose() {
    _tabController.dispose();
    _scrollController.dispose();
    super.dispose();
  }

  /// 构建页面主体
  /// 使用NestedScrollView实现头部折叠效果
  /// 包含一个可折叠的AppBar和TabBarView
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          Expanded(
            child: Stack(children: [
              NestedScrollView(
                controller: _scrollController,
                headerSliverBuilder: (context, innerBoxIsScrolled) {
                  return [
                    SliverAppBar(
                      automaticallyImplyLeading: false,
                      expandedHeight: 309.h,
                      floating: false,
                      pinned: true,
                      systemOverlayStyle: _isCollapsed
                          ? SystemUiOverlayStyle.dark
                          : SystemUiOverlayStyle.light,
                      flexibleSpace: FlexibleSpaceBar(
                        background: Obx(() =>
                            _buildUserInfoSection(meController.user.value)),
                      ),
                      bottom: PreferredSize(
                        preferredSize: Size.fromHeight(_isMe ? 67.h : 25.h),
                        child: Container(
                          height: _isMe ? 67.h : 25.h,
                          alignment: Alignment.center,
                          decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.only(
                              topLeft: Radius.circular(_isCollapsed ? 0 : 20),
                              topRight: Radius.circular(_isCollapsed ? 0 : 20),
                            ),
                          ),
                          child: Column(
                            children: [
                              SizedBox(
                                height: 25.h,
                              ),
                              Visibility(
                                visible: _isMe,
                                maintainSize: _isMe,
                                maintainAnimation: _isMe,
                                maintainState: true,
                                child: SizedBox(
                                  height: 25.h,
                                  child: TabBar(
                                    controller: _tabController,
                                    dividerColor: Colors.transparent,
                                    tabs: _tabs
                                        .map((tab) => Tab(text: tab))
                                        .toList(),
                                    labelColor: Color(0xFF8A72FE),
                                    unselectedLabelColor: Color(0xFFC1C1C1),
                                    labelStyle: TextStyle(
                                        fontSize: 16.sp,
                                        fontWeight: FontWeight.bold),
                                    unselectedLabelStyle: TextStyle(
                                        fontSize: 16.sp,
                                        fontWeight: FontWeight.bold),
                                    labelPadding: EdgeInsets.symmetric(
                                        horizontal: 11.5.w),
                                    tabAlignment: TabAlignment.center,
                                    indicator: const CustomTabBarIndicator(),
                                    // 使用自定义指示器
                                    indicatorSize: TabBarIndicatorSize.tab,
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                    ),
                  ];
                },
                body: Container(
                  decoration: BoxDecoration(
                    color: Colors.white,
                  ),
                  child: TabBarView(
                    controller: _tabController,
                    children: _tabs.map((tab) => _buildDynamicsList()).toList(),
                  ),
                ),
              ),
              Positioned(
                top: 0,
                left: 0,
                right: 0,
                child: _buildAppBar(),
              ),
            ]),
          ),
          if (_isMe)
            _meBottomBar()
          else
            Obx(() => _userBottomBar(meController.user.value))
        ],
      ),
    );
  }

  Widget _buildAppBar() {
    return Container(
      padding: EdgeInsets.only(top: MediaQuery.of(context).padding.top),
      height: _appBarHeight,
      decoration: BoxDecoration(
        gradient: _isCollapsed
            ? null
            : LinearGradient(
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter,
                colors: [
                  Colors.black.withOpacity(0.3),
                  Colors.transparent,
                ],
              ),
        color: _isCollapsed ? Colors.white : null,
      ),
      child: Row(
        children: [
          IconButton(
            icon: Icon(
              Icons.arrow_back,
              color: _isCollapsed ? Colors.black : Colors.white,
            ),
            onPressed: () => Navigator.pop(context),
          ),
          Expanded(
            child: Text(
              'User Details',
              textAlign: TextAlign.center,
              style: TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.w500,
                color: _isCollapsed ? Colors.black : Colors.transparent,
              ),
            ),
          ),
          // 添加一个占位的IconButton，保持布局对称
          IconButton(
            icon: Icon(
              Icons.arrow_back,
              color: Colors.transparent,
            ),
            onPressed: null,
          ),
        ],
      ),
    );
  }

  Widget _buildUserInfoSection(User user) {
    return Container(
      height: 309.h,
      decoration: BoxDecoration(
          image: DecorationImage(
        image:
            user.pageImgInAudit != null && user.pageImgInAudit!.isNotEmpty
                ? NetworkImage(user.pageImgInAudit!)
                : const AssetImage(MeAssetsConstants.iconEmpty),
        fit: BoxFit.cover,
      )),
      child: Padding(
        padding: EdgeInsets.fromLTRB(15.w, 106.h, 20.w, 0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                CircleAvatar(
                  radius: 37.2.r,
                  backgroundImage: user.headPortraitsUrl != null &&
                          user.headPortraitsUrl!.isNotEmpty
                      ? NetworkImage(user.headPortraitsUrl!)
                      : const AssetImage(MeAssetsConstants.iconEmpty),
                ),
                SizedBox(width: 14.w),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      SizedBox(height: 2.h),
                      Row(
                        children: [
                          Text(
                            user.nickname ?? "",
                            style: TextStyle(
                              fontSize: 22.sp,
                              fontWeight: FontWeight.normal,
                              color: Colors.white,
                            ),
                          ),
                          SizedBox(width: 1.w),
                          Container(
                            alignment: Alignment.center,
                            height: 13.66.h,
                            padding: EdgeInsets.symmetric(
                              horizontal: 6.w,
                            ),
                            decoration: BoxDecoration(
                              color: Color(0xFF9ED1FF),
                              borderRadius: BorderRadius.circular(7.39.r),
                            ),
                            child: Text(
                              'LV${(user.memberLevel ?? 0).toString()}',
                              style: TextStyle(
                                fontSize: 10.sp,
                                color: Colors.white,
                              ),
                            ),
                          ),
                        ],
                      ),
                      Text(
                        'ID:${user.userCode}',
                        style: TextStyle(
                          fontSize: 14.sp,
                          color: Colors.white,
                        ),
                      ),
                      SizedBox(height: 1.h),
                      Text(
                        user?.about ?? T.current.me1_signature,
                        style: TextStyle(
                          fontSize: 11.sp,
                          color: Colors.white,
                        ),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ],
                  ),
                ),
              ],
            ),
            SizedBox(height: 23.h),
            if (user.aboutList != null && user.aboutList!.isNotEmpty)
              Wrap(
                alignment: WrapAlignment.start,
                // 主轴对齐方式
                runAlignment: WrapAlignment.start,
                // 轴对齐方式
                spacing: 8.w,
                runSpacing: 8.h,
                children: [
                  Text(
                    "Personal Tags:",
                    style: TextStyle(fontSize: 12.sp, color: Colors.white),
                  ),
                  for (var tag in user.aboutList??[])
                    _buildTag(tag),
                ],
              ),
            SizedBox(height: 19.h),
            if (!_isMe)
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                  _visitorsCount(
                      "Visitors", (user?.accessCount ?? 0).toString()),
                  _visitorsCount("Following", user?.attentions ?? '0'),
                  _visitorsCount("Followers", (user?.fans ?? 0).toString()),
                  _visitorsCount("Gift", user?.giftNum ?? '0'),
                ],
              ),
          ],
        ),
      ),
    );
  }

  Widget _visitorsCount(String type, String count) {
    return Column(
      children: [
        Text(
          count,
          style: TextStyle(fontSize: 18.sp, color: Colors.white),
        ),
        Text(
          type,
          style: TextStyle(fontSize: 12.sp, color: Color(0xFFD8D8D8)),
        ),
      ],
    );
  }

  /// 构建标签组件
  /// @param text 标签文本
  /// @return 返回一个带有圆角背景的标签组件
  Widget _buildTag(String text) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 3.h),
      decoration: BoxDecoration(
        color: Color(0x66E2DCFF),
        borderRadius: BorderRadius.circular(16),
      ),
      child: Text(
        text,
        style: const TextStyle(color: Colors.white, fontSize: 12),
      ),
    );
  }

  /// 构建动态列表
  /// 返回一个包含用户动态卡片的列表视图
  Widget _buildDynamicsList() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        Image.asset(
          MeAssetsConstants.iconEmpty,
          fit: BoxFit.contain,
          width: 248.w,
          height: 248.h,
        ),
        Text(T.current.room15_requires_homeowner,
            style: TextStyle(fontSize: 12.sp, color: Color(0xFFC1C1C1)))
      ],
    );
  }

  Widget _meBottomBar() {
    return Container(
      color: Colors.white,
      height: 70.h,
      padding: EdgeInsets.only(),
      child: Row(mainAxisAlignment: MainAxisAlignment.center, children: [
        Container(
          width: 140.w,
          height: 40.h,
          decoration: BoxDecoration(
            gradient: LinearGradient(
              colors: [Color(0xCC6549EC), Color(0xCC8A72FE)], // 渐变色
              begin: Alignment.centerLeft, // 渐变起点
              end: Alignment.centerRight, // 渐变终点
            ),
            borderRadius: BorderRadius.circular(22.r), // 设置圆角
          ),
          child: Row(mainAxisAlignment: MainAxisAlignment.center, children: [
            Image.asset(
              MeAssetsConstants.iconEdit,
              width: 26.w,
              height: 26.h,
            ),
            SizedBox(width: 7.w),
            Text(
              'Edit',
              style: TextStyle(
                color: Colors.white,
                fontSize: 18.sp,
              ),
            )
          ]),
        ).onClick(() {
          Get.to(() => UserEditPage());
        }),
        SizedBox(width: 21.w),
        Container(
          width: 140.w,
          height: 40.h,
          decoration: BoxDecoration(
            gradient: LinearGradient(
              colors: [Color(0xCC6549EC), Color(0xCC8A72FE)], // 渐变色
              begin: Alignment.centerLeft, // 渐变起点
              end: Alignment.centerRight, // 渐变终点
            ),
            borderRadius: BorderRadius.circular(22.r), // 设置圆角
          ),
          child: Row(mainAxisAlignment: MainAxisAlignment.center, children: [
            Image.asset(
              MeAssetsConstants.iconPost,
              width: 26.w,
              height: 26.h,
            ),
            SizedBox(width: 7.w),
            Text(
              'Post',
              style: TextStyle(
                color: Colors.white,
                fontSize: 18.sp,
              ),
            )
          ]),
        ).onClick(() {
          Get.to(() => PostPage());
        }),
      ]),
    );
  }

  Widget _userBottomBar(User user) {
    return Container(
      color: Colors.white,
      height: 70.h,
      padding: EdgeInsets.only(),
      child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Padding(
              padding: EdgeInsets.only(right: 16.w),
              child: Column(children: [
                Image.asset(
                  MeAssetsConstants.iconChatRoom,
                  width: 30.w,
                  height: 30.h,
                  fit: BoxFit.cover,
                ),
                Text(
                  'join room',
                  style: TextStyle(
                    color: Color(0xFF6549EC),
                    fontSize: 12.sp,
                  ),
                ),
              ]),
            ),
            Container(
              width: 120.w,
              height: 40.h,
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  colors: [Color(0xCC6549EC), Color(0xCC8A72FE)], // 渐变色
                  begin: Alignment.centerLeft, // 渐变起点
                  end: Alignment.centerRight, // 渐变终点
                ),
                borderRadius: BorderRadius.circular(22.r), // 设置圆角
              ),
              child:
                  Row(mainAxisAlignment: MainAxisAlignment.center, children: [
                Image.asset(
                  MeAssetsConstants.iconChat,
                  width: 26.w,
                  height: 26.h,
                ),
                SizedBox(width: 6.w),
                Text(
                  'Chat',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 18.sp,
                  ),
                )
              ]),
            ).onClick(() {
              if (user.imId != null && user.imId!.isNotEmpty) {
                ImManager.jumpChat(user.imId!);
              }
            }),
            SizedBox(width: 9.w),
            Container(
              width: 126.w,
              height: 40.h,
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  colors: user.isAttention ?? false
                      ? [Color(0xCCBFB8E4), Color(0xCCDBD6F0)]
                      : [Color(0xCC6549EC), Color(0xCC8A72FE)], // 渐变色
                  begin: Alignment.centerLeft, // 渐变起点
                  end: Alignment.centerRight, // 渐变终点
                ),
                borderRadius: BorderRadius.circular(22.r), // 设置圆角
              ),
              child:
                  Row(mainAxisAlignment: MainAxisAlignment.center, children: [
                Image.asset(
                  user.isAttention ?? false
                      ? MeAssetsConstants.iconUnfollow
                      : MeAssetsConstants.iconFollow,
                  width: 26.w,
                  height: 26.h,
                ),
                SizedBox(width: 2.w),
                Text(
                  user.isAttention ?? false ? 'Unfollow' : 'Follow',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 18.sp,
                  ),
                )
              ]),
            ).onClick(() {
              String userId = user.userId?.toString() ?? "";
              bool isAttention = user.isAttention ?? false;
              meController.isAttention(userId, isAttention);
            }),
          ]),
    );
  }
}
